const validator = require('validator').default
const isEmpty = require('lodash/isEmpty')
const Exception = require('../exception/Exception')
const ErrorCode = require('../utils/ErrorCode')

const signupValidator = function (req, res, next) {
  const { email, code, password, confirm_password } = req.body
  const error = {}
  if (!validator.isEmail(email)) error.email = '邮箱不正确'
  if (validator.isEmpty(code)) error.code = '验证码不可为空'
  if (validator.isEmpty(password)) error.password = '密码不可为空'
  if (validator.isEmpty(confirm_password)) error.confirm_password = '确认密码不可为空'
  if (!validator.equals(password, confirm_password)) error.confirm_password = '两次密码不一致'

  if (!isEmpty(error)) {
    return next(new Exception(10000, ErrorCode[10000], error))
  }
  next()
}

const signin = (req, res, next) => {
  const { email, password } = req.body
  const error = {}
  if (!validator.isEmail(email)) error.email = '邮箱不正确'
  if (validator.isEmpty(password)) error.password = '密码不可为空'

  if (!isEmpty(error)) {
    return next(new Exception(10000, ErrorCode[10000], error))
  }
  next()
}

const getCode = (req, res, next) => {
  const { email } = req.body
  const error = {}
  if (!validator.isEmail(email)) error.email = '邮箱不正确'

  if (!isEmpty(error)) {
    return next(new Exception(10002, ErrorCode[10002], error))
  }
  next()
}

module.exports = {
  signupValidator,
  signin,
  getCode
}